import {
  getInterfaceInfoByIdUsingGet,
  invokeInterfaceInfoUsingPost,
} from '@/services/openApi-back/interfaceInfoController';
import { FormProps, PageContainer } from '@ant-design/pro-components';
import { Button, Card, Descriptions, Form, Input, message } from 'antd';
import React, { useEffect, useState } from 'react';
import { useParams } from 'react-router';

const Index: React.FC = () => {
  const [loading, setLoading] = useState(false);
  const [data, setData] = useState<API.InterfaceInfo>();
  const params = useParams();
  const [resData, setResData] = useState<any>();
  // const
  const onFinish: FormProps['onFinish'] = async (values) => {
    if (!params.id) {
      return message.error('接口id不能为空');
    }
    setLoading(true);
    try {
      const res = await invokeInterfaceInfoUsingPost({
        id: params.id,
        ...values,
      });
      setResData(res.data);
      message.success('调用成功');
    } catch (error) {
      message.error('调用失败!检查一下!!!' + error.message);
    }
    setLoading(false);
  };
  const loadData = async () => {
    if (!params.id) {
      return message.error('接口id不能为空');
    }
    setLoading(true);
    try {
      const res = await getInterfaceInfoByIdUsingGet({
        id: Number(params.id),
      });
      setData(res.data);
    } catch (error) {
      message.error('加载失败!再试一次!!!' + error.message);
    }
    setLoading(false);
  };
  useEffect(() => {
    loadData();
  }, []);
  return (
    <PageContainer title={'开放接口平台'}>
      <Card>
        {data ? (
          <Descriptions title={data.name} column={1} extra={<Button>调用</Button>}>
            <Descriptions.Item label="描述">{data.description}</Descriptions.Item>
            <Descriptions.Item label="URL">{data.url}</Descriptions.Item>
            <Descriptions.Item label="请求方法">{data.method}</Descriptions.Item>
            <Descriptions.Item label="请求参数">{data.requestParams}</Descriptions.Item>
            <Descriptions.Item label="请求头">{data.requestHeader}</Descriptions.Item>
            <Descriptions.Item label="响应头">{data.responseHeader}</Descriptions.Item>
            <Descriptions.Item label="接口状态">{data.status ? '在线' : '下线'}</Descriptions.Item>
            <Descriptions.Item label="创建时间">{data.createTime}</Descriptions.Item>
            <Descriptions.Item label="更新时间">{data.updateTime}</Descriptions.Item>
          </Descriptions>
        ) : (
          <>接口不存在</>
        )}
      </Card>
      <Card style={{ marginTop: 10 }} title={'在线测试'}>
        <Form name="invoke" layout={'vertical'} onFinish={onFinish}>
          <Form.Item label="接口测试：" name="userRequestParams">
            <Input.TextArea />
          </Form.Item>
          <Form.Item wrapperCol={{ span: 16 }}>
            <Button type="primary" htmlType="submit">
              测试接口
            </Button>
          </Form.Item>
        </Form>
      </Card>
      <Card title={'调用结果'} style={{ marginTop: 10 }}>{resData}</Card>
    </PageContainer>
  );
};

export default Index;
